//
//  BleOTAViewController.m
//  StormWatch
//
//  Created by 王岩 on 2024/8/31.
//

#import "BleOTAViewController.h"
#import <AFNetworking.h>
//#import <MBProgressHUD.h>
#import <SVProgressHUD.h>
@interface BleOTAViewController ()< FRQBluetoothManagerDelegate>
/* <#note#> */
@property (nonatomic, strong) NSURL * filePath;
@end

@implementation BleOTAViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[FRQBluetoothManager shareManager] addBleDelegate:self];
    
    [[StormCommandTool sharedInstance] readStormCommand:Command_OTA_Version reBack:^(NSString * _Nonnull backData) {
        // 5459010180012b000d00030009 01 02 01 00 00 46474b43
        if (backData.length > 26) {
            NSString * valueStr = [backData substringFromIndex:26];
            
            unsigned long dateValue = strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(0, 2)]] UTF8String], 0, 16);
            unsigned long dateValue2 = strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(2, 2)]] UTF8String], 0, 16);
            unsigned long dateValue3 = strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(4, 2)]] UTF8String], 0, 16);
            unsigned long dateValue4 = strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(6, 2)]] UTF8String], 0, 16);
            unsigned long dateValue5 = strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(8, 2)]] UTF8String], 0, 16);
            
            [SWInitializer jy_initLabelWithText:[NSString stringWithFormat:@"%@:%lu.%lu.%lu",SWString(@"Software Version"),dateValue3,dateValue4,dateValue5] textColor:[UIColor blackColor] font:S_font(15) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
                kMakeLV(20);kMakeTV(20);
            }];
            
        }
    }];
    
    [SWInitializer jy_initRedButtonWithTarget:self action:@selector(clickSureBtnAction) frame:CGRectMake(0, 0, kScreenWidth - 100, 50) title:SWString(@"OTA upgrade") on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(50);
        kMakeBV(-100);
        kMakeWHV(kScreenWidth-100, 50);
    }];
    
    // Do any additional setup after loading the view.
}

- (void)clickSureBtnAction {
    
    if ([StormCommandTool sharedInstance].electric < 40) {
        toast(SWString(@"Keep the battery level higher than 40% before upgrading"));
        return;
    }
    
//    //弹窗确认
//    NSString *noticeText = [NSString stringWithFormat:@"确定连接蓝牙设备(%@)并进行升级？",[FRQBluetoothManager shareManager].curPeripheral.name?:@"N/A"];
//    UIAlertController *confirmAlertCtrl = [UIAlertController alertControllerWithTitle:@"提醒" message:noticeText preferredStyle:UIAlertControllerStyleAlert];
//    [confirmAlertCtrl addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//        [self updateOTAToPeripheral:[FRQBluetoothManager shareManager].curPeripheral];
//    }]];
//    [confirmAlertCtrl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        
//    }]];
//    [self presentViewController:confirmAlertCtrl animated:YES completion:nil];
//    return;
    
    MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
    if (!progressHUD) {
        progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    progressHUD.label.text = SWString(@"Downloading OTA file, please wait");
    progressHUD.mode = MBProgressHUDModeText;
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [NSString stringWithFormat:@"%@/updateGrade.ufw",documentPath];
    
    NSString * url = @"http://39.107.79.56:8080/ota/watch/firmware/upgrade?productId=12880";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [[manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@", [NSString stringWithFormat:@"当前下载进度:%.2f%%",100.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount]);
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            NSLog(@"临时文件路径: %@", targetPath);
            NSURL *path = [[NSURL fileURLWithPath:documentPath] URLByAppendingPathComponent:response.suggestedFilename];
//            [path URLByAppendingPathComponent:response.suggestedFilename];
            self.filePath = path;
            return path;
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            NSLog(@"本地存储路径: %@", filePath);
            [MBProgressHUD hideHUDForView:self.view animated:NO];

            if (!error) {
                [self updateOTAToPeripheral:[FRQBluetoothManager shareManager].curPeripheral];
            }else {
                toast(SWString(@"OTA file download failed"));
            }
        }] resume];

}

-(void)updateOTAToPeripheral:(CBPeripheral *)peripheral{
    
    //开始OTA升级
//    NSString *otaBinDataPath = [[NSBundle mainBundle] pathForResource:@"006B_ver_8" ofType:@"bin"];
    NSData *otaBinData = [NSData dataWithContentsOfURL:self.filePath];

    [[FRQBluetoothManager shareManager] updateOTAWithData:otaBinData toPeripheral:peripheral];
    
}

// OTA升级阶段回调
-(void)onBLEManagerBeginUpdateOTA:(id<FRBleAbility>)ability{

    [MBProgressHUD hideHUDForView:self.view animated:NO];
    
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    progressHUD.label.text = SWString(@"Ready");
    progressHUD.mode = MBProgressHUDModeText;
    [progressHUD hideAnimated:YES afterDelay:2.0];
    
}

-(void)onBLEManagerUpdateOTA:(id<FRBleAbility>)ability progress:(double)aProgress{
    
    MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
    if (!progressHUD) {
        progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    progressHUD.label.text = [NSString stringWithFormat:@"%@:%.f%%", SWString(@"Upgrading"),aProgress];
//    progressHUD.detailsLabel.text = [NSString stringWithFormat:@"当前进度%.f,请稍后..",aProgress];
    progressHUD.mode = MBProgressHUDModeAnnularDeterminate;
    progressHUD.progress = aProgress/100.0;
    if (aProgress ==  100.0) {
        progressHUD.label.text = SWString(@"Update completed");
        [progressHUD hideAnimated:YES afterDelay:2.0];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }
}

-(void)onBLEManagerUpdateOTAFinish:(id<FRBleAbility>)ability error:(NSError *)error{
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    
    //alert
    NSString *alertMsg = error?error.localizedDescription:@"设备升级成功";
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"提醒" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
    [alertCtrl addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }]];
    [self presentViewController:alertCtrl animated:YES completion:^{}];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
